package com.qf.qfarticle.controller.v1;

import com.qf.qfleadnewscommons.mvc.ThreadLocalUtils;
import com.qf.qfleadnewsmodel.behavior.dtos.BehaviorDto;
import com.qf.qfleadnewsmodel.commons.consts.RedisConst;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class BehaviorController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/collection_behavior")
    public ResponseResult collection(@RequestBody BehaviorDto behaviorDto){

        String key = RedisConst.ARTICLE_COLLECTION_PREFIX + behaviorDto.getEntryId();
        long offset = ThreadLocalUtils.getUid();
        redisTemplate.opsForValue().setBit(key,offset,behaviorDto.getOperation() == 0);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @PostMapping("/article/load_article_behavior")
    public ResponseResult loadBehavior(@RequestBody BehaviorDto behaviorDto){
        String articleId = behaviorDto.getArticleId();

        Long uid = ThreadLocalUtils.getUid();

        //当前用户是否有收藏
        String key = RedisConst.ARTICLE_COLLECTION_PREFIX + articleId;
        Boolean isCollection = redisTemplate.opsForValue().getBit(key, uid);
        //当前用户是否有喜欢
        key = RedisConst.ARTICLE_LIKE_PREFIX + articleId;
        Boolean isLike = redisTemplate.opsForValue().getBit(key, uid);
        //当前用户是否有不喜欢
        key = RedisConst.ARTICLE_UNLIKE_PREFIX + articleId;
        Boolean isUnLike = redisTemplate.opsForValue().getBit(key, uid);

        Map map = new HashMap();
        map.put("islike",isLike);
        map.put("isunlike",isUnLike);
        map.put("iscollection",isCollection);

        return ResponseResult.okResult(map);
    }
}
